package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.AssetScrap;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.AssetScrapService;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/27.
 */
@Controller
@RequestMapping(value = "/com/assetScrap")
public class AssetScrapController extends BaseController {
    private static final long serialVersionUID = 4400127454227957520L;

    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetScrapService assetScrapService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;

    private Date dateApply;
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private DecimalFormat fnum = new DecimalFormat("##0.00");
    private Asset asset;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> typeDict = getDictItems(user,"scrapReason");
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            AssetScrap assetScrap=assetScrapService.get(keyId);
            if(assetScrap.getFile() != null && assetScrap.getFile().size()>0){
                for(FileManage f:assetScrap.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("keyId", keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("assetScrap", assetScrap);
        }
        model.addAttribute("typeDict", typeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetscrap_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> typeDict = getDictItems(user,"dispatchType");
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            AssetScrap assetScrap=assetScrapService.get(keyId);
            if(assetScrap.getCreateType()!=1){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
                int stepNo = taskEntity.getStepNo();
                String isEdit =  isEdit(keyId);
                model.addAttribute("stepNo", stepNo);
                model.addAttribute("isEdit", isEdit);
            }
            if(assetScrap.getFile() != null && assetScrap.getFile().size()>0){
                for(FileManage f:assetScrap.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
            model.addAttribute("assetScrap", assetScrap);

        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("typeDict", typeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetscrap_read";
    }

    /**
     * 保存Model数据
     */
    private AssetScrap saveModel(User user, String keyId, String assetId, String name,
                                 String dictItemId, String numYTZJMoney, String numNetMoney, String numLeftMoney,
                                 String fileIds) throws ParseException {

        AssetScrap assetScrap = null;
        if (StringUtils.isBlank(keyId)) {
            assetScrap = new AssetScrap();
            assetScrap.setCreater(user);
            assetScrap.setCompany(user.getCompany());
        } else {
            assetScrap = assetScrapService.get(keyId);
        }

        if (StringUtils.isNotBlank(assetId)) {
            Asset asset = assetService.get(assetId);
            if (asset != null) {
                assetScrap.setAsset(asset);
            }
        }

        if (StringUtils.isNotBlank(name)) {
            assetScrap.setName(name);
        }

        if (StringUtils.isNotBlank(dictItemId)) {
            DictItem dictItem = dictItemService.get(dictItemId);
            assetScrap.setDictItem(dictItem);
        }

        if (StringUtils.isNotBlank(numYTZJMoney)) {
            assetScrap.setNumYTZJMoney(Double.valueOf(numYTZJMoney));
        }

        if (StringUtils.isNotBlank(numNetMoney)) {
            assetScrap.setNumNetMoney(Double.valueOf(numNetMoney));
        }

        if (StringUtils.isNotBlank(numLeftMoney)) {
            assetScrap.setNumLeftMoney(Double.valueOf(numLeftMoney));
        }

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        assetScrap.setFile(fileManageList);

        if (assetScrap.getForm() == null) {
            assetScrap.setForm("资产报废登记表");
        }

        return assetScrap;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                       String dictItemId, String numYTZJMoney, String numNetMoney, String numLeftMoney,
                       String fileIds) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetScrap assetScrap = saveModel(user, keyId, assetId, name, dictItemId, numYTZJMoney, numNetMoney, numLeftMoney, fileIds);
        if(StringUtils.isNotEmpty(keyId)){
            assetScrapService.update(assetScrap);
            rMap.put("message", "更新成功");
        } else {
            assetScrapService.save(assetScrap, "com.fz.us.oa.core.entity.com.AssetScrap");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                         String dictItemId, String numYTZJMoney, String numNetMoney, String numLeftMoney,
                         String fileIds, String curDutyId, String comment) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetScrap assetScrap = saveModel(user, keyId, assetId, name, dictItemId, numYTZJMoney, numNetMoney, numLeftMoney, fileIds);
        assetScrap.setTxtStatus("流转中");

        if (StringUtils.isNotEmpty(keyId)) {
            assetScrapService.approve(assetScrap, dutyService.get(curDutyId), comment);
        } else {
            assetScrapService.commit(assetScrap, "com.fz.us.oa.core.entity.com.AssetScrap", dutyService.get(curDutyId));
        }

        if(assetScrap.getProcessState().name().equals("Finished")){
            doFinished(assetScrap);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetScrap assetScrap=assetScrapService.get(keyId);
        assetScrapService.approve(assetScrap, dutyService.get(curDutyId), comment);

        if(assetScrap.getProcessState().name().equals("Finished")){
            doFinished(assetScrap);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(AssetScrap assetScrap){
        assetScrap.setNumStatus(1);
        assetScrap.setTxtStatus("已报废");
        assetScrapService.update(assetScrap);

        Asset asset = assetScrap.getAsset();
        asset.setTxtStatus("已报废");
        assetService.update(asset);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetScrap assetScrap=assetScrapService.get(keyId);
            assetScrapService.back(assetScrap, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetScrap assetScrap=assetScrapService.get(keyId);
            assetScrapService.deny(assetScrap, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype, @RequestParam(required = false) String assetId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

        if (!StringUtils.isEmpty(assetId)) {
            rules.add(RuleHelper.eq("asset.id", assetId));  // 所属一个资产下的使用登记表
        }

        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //流转中
                searchResult = assetScrapService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetScrap", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);

            }else if(viewtype.equals("2")){
                //已报废
                rules.add(RuleHelper.eq("numStatus", 1));
                searchResult = assetScrapService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetScrap", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},null);
            }
        }else{
            searchResult = assetScrapService.paging(null,rules,order,
                    "com.fz.us.oa.core.entity.com.AssetScrap", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Running},null);
        }

        List<AssetScrap> assetScrapList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(AssetScrap assetScrap: assetScrapList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(assetScrap.getId())?"":assetScrap.getId());

            if(assetScrap.getCreateTime() != null){
                dateApply = assetScrap.getCreateTime();
                rMap.put("year", yearFormat.format(dateApply));   // 年份
                rMap.put("month", monthFormat.format(dateApply));   // 月份
                rMap.put("dateApply",dateFormat.format(dateApply));
            } else {
                rMap.put("year", "");   // 年份
                rMap.put("month", "");   // 月份
                rMap.put("dateApply","");
            }

            asset = assetScrap.getAsset();
            if(asset!=null){
                rMap.put("assetNo", asset.getAssetNo());
                rMap.put("model", asset.getModel());
                rMap.put("purchaseMoney", fnum.format(asset.getPurchaseMoney()));
            }

            rMap.put("name", assetScrap.getName());
            rMap.put("scrapReason", assetScrap.getDictItem()==null?"":assetScrap.getDictItem().getName());
            rMap.put("txtStatus", assetScrap.getTxtStatus());

//        map.put("processStateName", entity.getProcessState()==null?"": entity.getProcessState().value());
//        map.put("createTime", entity.getCreateTime()==null?"": DataUtil.DateTimeToString(entity.getCreateTime()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

}
